import { requestClient } from "@/apis/client";
import axios from "axios";

/**
 * 处理字符串 "1:2:3:4:5:6"   ==> [1,2,3,4,5,6]
 * @param：str
 */
export function stockStringToArray(str: string) {
  if (str?.length == 0 || !str) return [0, 0, 0, 0, 0, 0]
  let temp = str?.split(":") || [0, 0, 0, 0, 0, 0];
  return temp.map((s) => +s || 0);
}

/**
 * 处理字符串求和 "1:2:3:4:5:6"   ==> 21
 * @param：str
 */
export function stockStringSum(str: string) {
  let numArr = stockStringToArray(str)
  return numArr.reduce((prev, item) => item + prev, 0);
}
/**
 * 处理字符串求和 "1:2:3:4:5:6" + "1:2:3:4:5:6"  ==> "2:4:6:8:10:12"
 * @param：str1 str2
 */
export function stockStringAdd(str1: string, str2: string) {
  // 将输入字符串按冒号分割成数组
  const arr1 = str1.split(":");
  const arr2 = str2.split(":");
  
  // 创建一个空数组来存储相加后的结果
  const resultArr = [];

  // 遍历两个数组，将对应位置的元素相加，并将结果添加到结果数组中
  for (let i = 0; i < arr1.length; i++) {
    const num1 = parseInt(arr1[i], 10);
    const num2 = parseInt(arr2[i], 10);
    const sum = num1 + num2;
    resultArr.push(sum);
  }

  // 将结果数组转换为字符串，用冒号连接各个元素
  const resultStr = resultArr.join(":");

  return resultStr;
}
/**
 * 统一Excel导出接口
 * @param：columns 表头配置
 * @param：data 数据
 * @param：flieName 导出文件名
 */
export function exportExcelFile(columns: any, data: any, fileName: string) {
  requestClient
    .post(
      "/download/excel",
      {
        // .post("http://localhost:8081/Hopeto/download/excel", {
        // .post("http://172.20.13.52:8081/Hopeto/download/excel", {
        columns,
        data,
        fileName,
      }
      // { responseType: "blob" }
    )
    .then((response) => {
      // 将Base64字符串解析为二进制数据
      let binaryData = window.atob(response.data);

      // 创建一个Uint8Array来保存二进制数据
      let uint8Array = new Uint8Array(binaryData.length);

      // 将二进制数据逐字节复制到Uint8Array
      for (let i = 0; i < binaryData.length; i++) {
        uint8Array[i] = binaryData.charCodeAt(i);
      }
      // 创建 Blob 对象
      const blobData = new Blob([uint8Array]);
      console.log(blobData);

      // 创建下载链接
      const downloadLink = document.createElement("a");
      downloadLink.href = URL.createObjectURL(blobData);
      downloadLink.download = fileName;

      // 模拟点击下载链接
      document.body.appendChild(downloadLink);
      downloadLink.click();

      // 移除下载链接
      document.body.removeChild(downloadLink);
    })
    .catch((error) => {
      console.error("Error:", error);
    });
}
